/**
 * 
 */
package cn.ac.istic.lkt.atv;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;

/**
 * @author Chongde Shi
 * 
 */
public class ATVMain extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5986403822223017397L;
	JMenuBar menuBar = new JMenuBar();
	// file
	JMenu menuFile = new JMenu();
	JMenuItem menuItemLoad = new JMenuItem();
	JMenuItem menuItemExportSen = new JMenuItem();
	JMenuItem menuItemExportImg = new JMenuItem();
	JMenuItem menuItemExit = new JMenuItem();
	JMenuItem menuItemExport = new JMenuItem();
	// tool
	// static JMenu menuTool = new JMenu();
	// static JMenuItem parse = new JMenuItem();
	// help
	JMenu menuHelp = new JMenu();
	JMenuItem aboutItem = new JMenuItem();
	AboutDlg aboutDlg;

	SentenceListPanel senPanel = new SentenceListPanel(this);
	List<SentenceTree> stlist = null;

	TreePanel treePanel = new TreePanel();
	JScrollPane scrollPane = new JScrollPane(treePanel);
	BorderLayout borderLayout1 = new BorderLayout();

	public ATVMain() {
		setTitle("ATViewer");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		// try {
		// init();
		// }catch (Exception e){
		// e.printStackTrace();
		// }
	}

	public void init() {
		getContentPane().setLayout(borderLayout1);

		this.setJMenuBar(menuBar);

		menuItemLoad.setText("Load Trees");
		menuItemLoad.addActionListener(new myListener(this));
		menuItemExportSen.setText("Export Sentences");
		menuItemExportSen.addActionListener(new myListener(this));
		menuItemExportImg.setText("Export Images");
		menuItemExportImg.addActionListener(new myListener(this));

		menuItemExit.setText("Exit");
		menuItemExit.addActionListener(new myListener(this));
		menuFile.setText("File");
		menuFile.add(menuItemLoad);
		menuFile.add(menuItemExportSen);
		menuFile.add(menuItemExportImg);
		menuFile.addSeparator();
		menuFile.add(menuItemExit);

		menuBar.add(menuFile);

		getContentPane().add(senPanel, BorderLayout.NORTH);

		// scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		// scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setAutoscrolls(true);
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		Toolkit tk = this.getToolkit();
		Dimension wndSize = tk.getScreenSize();
		// this.setBounds((wndSize.width-800)/2,(wndSize.height-600)/2,800,600);
		this.setBounds(wndSize.width / 20, wndSize.height / 20,
				wndSize.width * 18 / 20, wndSize.height * 18 / 20);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				performExit();
			}
		});
		setVisible(true);

	}

	public void repaint(ParseTree pt) {
		super.repaint();
		scrollPane.add(new TreePanel(pt));
	}

	public void performExit() {
		System.exit(0);
	}

	public void exportSentence() {
		if (stlist == null || stlist.size() == 0) {
			System.err.println("Trees are not loaded yet!");
			return;
		}
		JFileChooser jfc = new JFileChooser();
		jfc.setMultiSelectionEnabled(false);
		int option = jfc.showSaveDialog(ATVMain.this);
		String fname = null;
		if (option == JFileChooser.APPROVE_OPTION) {
			File f = jfc.getSelectedFile();
			fname = jfc.getName(f);
			if (f.isFile())
				fname = f.getName();
			f = jfc.getCurrentDirectory();
			f = new File(f.getPath().concat(File.separator).concat(fname));
			if (f.exists()) {
				int i = javax.swing.JOptionPane.showConfirmDialog(ATVMain.this,
						"该文件已经存在，确定要覆盖吗？");
				if (i == javax.swing.JOptionPane.YES_OPTION)
					;
				else
					return;
			}
			try {
				f.createNewFile();
				java.io.FileWriter fw = new java.io.FileWriter(f);
				for (int i = 0; i < stlist.size(); i++) {
					fw.write(stlist.get(i).getSents() + "\n");
				}
				fw.close();
				// 向要保存的文件写数据
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {

		}
	}

	public void exportImage() {
		if (stlist == null || stlist.size() == 0) {
			System.err.println("Trees are not loaded yet!");
			return;
		}
		for (int i = 0; i < stlist.size(); i++) {
			ParseTree pt = stlist.get(i).getTrees();
			TreePanel tp = new TreePanel(pt);
			BufferedImage img = tp.paintImage();
			try {
				File outputfile = new File("C:\\tmp\\img" + i + ".png");
				ImageIO.write(img, "png", outputfile);
			} catch (IOException e) {
				e.printStackTrace();
			}

			// System.out.println(tree);

		}

	}

	class myListener implements ActionListener {
		ATVMain container;

		public myListener(ATVMain app) {
			container = app;
		}

		public void actionPerformed(ActionEvent e) {
			// System.out.print(e.getSource());
			if (e.getSource().equals(menuItemExit)) {
				performExit();
			} else if (e.getSource().equals(menuItemLoad)) {
				JFileChooser chooser = new JFileChooser();
				chooser.setMultiSelectionEnabled(false);
				int option = chooser.showOpenDialog(ATVMain.this);
				if (option == JFileChooser.APPROVE_OPTION) {
					File f = chooser.getSelectedFile();
					stlist = SentenceTree.parseFile(f);

					DefaultListModel model = container.getSenPanel().getModel();
					model.removeAllElements();
					for (int i = 0; i < stlist.size(); i++) {
						model.addElement(stlist.get(i).getSents());
					}
					senPanel.getList().setSelectedIndex(0);
				} else {

				}

			} else if (e.getSource().equals(menuItemExportSen)) {
				exportSentence();
			} else if (e.getSource().equals(menuItemExportImg)) {
				exportImage();
			} else {
				;
			}
		}
	}

	public void drawTree(int id) {
		// System.err.println("Message from JList arraived. ID="+id);
		if (stlist == null || stlist.size() < id || id < 0) {
			return;
		}
		ParseTree pt = stlist.get(id).getTrees();
		treePanel.init(pt);
		// System.err.println(treelist.getSents().get(id));
		treePanel.repaint();
		getContentPane().validate();
	}

	public SentenceListPanel getSenPanel() {
		return senPanel;
	}

	public void setSenPanel(SentenceListPanel senPanel) {
		this.senPanel = senPanel;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ATVMain atvm = new ATVMain();
		atvm.init();
		// ParseTree pt = new
		// ParseTree("( (IP-HLN (NP-SBJ (NP-PN (NR 上海) (NR 浦东))  (NP (NN 开发) (CC 与) (NN 法制) (NN 建设))) (VP (VV 同步))) ) ");

	}

}
